package org.mango.action;

import com.xiaoleilu.hutool.http.HttpUtil;
import org.mango.base.BaseAction;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by meigang on 17/9/8.
 */
@RestController
@RequestMapping("/react")
public class ReactAction extends BaseAction{

    @GetMapping("/**")
    public String index(HttpServletRequest request) throws IOException {
        String uri = request.getRequestURI();
        uri = uri.replaceAll(this.getCtx(),"");
        StringBuffer sb = new StringBuffer();

        if(uri.contains(".jsx")) {
            //还有后缀
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            String jsStr = getJarReactStr(resolver,uri.substring(1,uri.length()),"");
            //jsStr 去转换 localhost:3000
            jsStr = HttpUtil.post("http://localhost:3000",jsStr);
            //拼上注册的部分
            /**
             * require.register("/js/demo.js", function(module, exports, require){
             *  var obj = {};
             obj.fun1 = function(){
             alert("it works");
             }
             module.exports = obj;
             * });
             */
            sb.append("require.register(").append("\"").append(uri).append("\",function(module,exports,require){")
                    .append(jsStr).append("\r\n").append("});")
                    .append("\r\n");
        }
        return sb.toString();
    }



}
